/**
 * CustomAlertTaskJob.java
 * Created at 2017-11-1
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.timetask.job;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.monitor.model.TtPackCurrent;
import com.broadtext.rms.system.model.TmCustomAlert;
import com.broadtext.rms.system.service.ITmCustomAlertService;
import com.broadtext.rms.timetask.model.TtPackCustomAlertTask;
import com.broadtext.rms.timetask.service.ICustomAlertTaskService;

/**
 * <p>ClassName: CustomAlertTaskJob</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-1</p>
 */
public class CustomAlertTaskJob {
    
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(CustomAlertTaskJob.class);
    /**
     * 自定义告警服务类
     */
    @Autowired
    @Qualifier("tmCustomAlertService")
    private ITmCustomAlertService tmCustomAlertService;
    
    /**
     * 电池监控服务类
     */
    @Autowired
    @Qualifier("customAlertTaskService")
    private ICustomAlertTaskService customAlertTaskService;
    
    
    /**
     * 
     * <p>Description: 定时任务targetMethod</p>
     */
    public void execute() {
        logger.info("开始插入自定义报警数据！");
        //数据查询时间条件
        try {
            Map<String,Object> map = this.customAlertTaskService.getQueryTime();
            Map<String,String> queryMap = new HashMap<String, String>();
            if(map!=null){
                queryMap.put("queryTimeStart", String.valueOf(map.get("queryTimeStart")));
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date queryTimeEnd = new Date();
            queryMap.put("queryTimeEnd", format.format(queryTimeEnd));
            List<TtPackCustomAlertTask> taskList = createCustomAlertData(queryMap);
            this.customAlertTaskService.batchInsertData(taskList);
            this.customAlertTaskService.updateTaskTime(format.format(queryTimeEnd));
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.info("插入数据出错！");
        }
        logger.info("结束插入自定义报警数据！");        
    }
    
    
    /**
     * 生成自定义告警数据
     * <p>Description: TODO</p>
     * @return
     */
    private List<TtPackCustomAlertTask>  createCustomAlertData(Map<String,String> queryMap) {
        List<TtPackCustomAlertTask> taskList = new ArrayList<TtPackCustomAlertTask>();
        try {
            //遍历自定义告警规则
            List<TtPackCurrent> list = this.customAlertTaskService.findTtPackDataList(queryMap);
            List<TmCustomAlert> cusAlertlist = this.tmCustomAlertService.getTmCustomAlertList();
            if(list!=null&&list.size()>0){
                for (TtPackCurrent ttPackCurrent : list) {
                    if(cusAlertlist!=null&&cusAlertlist.size()>0){
                        for (TmCustomAlert tmCustomAlert : cusAlertlist) {
                            //符合电压自定义告警
                            if(!checkParam(ttPackCurrent,tmCustomAlert,"ALERT_PARAM_U")){
                                //创建电压自定义告警数据
                                TtPackCustomAlertTask t = new TtPackCustomAlertTask();
                                t.setDelFlag("0");
                                t.setCreateUser("sys");
                                t.setCreateDate(new Date());
                                t.setUpdateUser("sys");
                                t.setUpdateDate(new Date());
                                t.setPkId(UUIDUtils.getUUID());
                                t.setRefId(ttPackCurrent.getPkId());
                                t.setColClientId(ttPackCurrent.getColClientId());
                                t.setPackCode(ttPackCurrent.getPackCode());
                                t.setAlertId(tmCustomAlert.getPkId());
                                t.setAlertCode(tmCustomAlert.getAlertCode());
                                t.setAlertParam("ALERT_PARAM_U");
                                t.setAlertLevel(tmCustomAlert.getAlertLevel());
                                t.setAlertName(tmCustomAlert.getAlertName());
                                t.setCustomerInfo("");
                                t.setAlertCategory("3");
                                t.setHappenTime(ttPackCurrent.getGatherTime());
                                taskList.add(t);
                            }
                            if(!checkParam(ttPackCurrent,tmCustomAlert,"ALERT_PARAM_T")){
                              //创建温度自定义告警数据
                                TtPackCustomAlertTask t = new TtPackCustomAlertTask();
                                t.setDelFlag("0");
                                t.setCreateUser("sys");
                                t.setCreateDate(new Date());
                                t.setUpdateUser("sys");
                                t.setUpdateDate(new Date());
                                t.setPkId(UUIDUtils.getUUID());
                                t.setRefId(ttPackCurrent.getPkId());
                                t.setColClientId(ttPackCurrent.getColClientId());
                                t.setPackCode(ttPackCurrent.getPackCode());
                                t.setAlertId(tmCustomAlert.getPkId());
                                t.setAlertCode(tmCustomAlert.getAlertCode());
                                t.setAlertParam("ALERT_PARAM_T");
                                t.setAlertLevel(tmCustomAlert.getAlertLevel());
                                t.setAlertName(tmCustomAlert.getAlertName());
                                t.setCustomerInfo("");
                                t.setAlertCategory("3");
                                t.setHappenTime(ttPackCurrent.getGatherTime());
                                taskList.add(t);
                            }
                        }
                    }
                }
            }
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return taskList;
    }
    
    
    
    
    
    
    private boolean checkParam(TtPackCurrent ttPackCurrent,TmCustomAlert tmCustomAlert,String alertParam){
        boolean flag = true;
        if(!alertParam.equals(tmCustomAlert.getAlertParam())){
            return flag;
        }
        BigDecimal maxVal = new BigDecimal("0");
        BigDecimal minVal = new BigDecimal("0");
        //告警规则参数为电压
        if("ALERT_PARAM_T".equals(tmCustomAlert.getAlertParam())){
            maxVal = new BigDecimal(StringUtils.isBlank(ttPackCurrent.getMaxTempVal())?"0":ttPackCurrent.getMaxTempVal());
            minVal = new BigDecimal(StringUtils.isBlank(ttPackCurrent.getMinTempVal())?"0":ttPackCurrent.getMinTempVal());
        }else if("ALERT_PARAM_U".equals(tmCustomAlert.getAlertParam())){
            maxVal = new BigDecimal(StringUtils.isBlank(ttPackCurrent.getMaxVolVal())?"0":ttPackCurrent.getMaxVolVal());
            minVal = new BigDecimal(StringUtils.isBlank(ttPackCurrent.getMinVolVal())?"0":ttPackCurrent.getMinVolVal());
        }
        //差值
        BigDecimal differences = maxVal.subtract(minVal);
        //没有逻辑符，单一比较值
        if(StringUtils.isBlank(tmCustomAlert.getLogicalSymbol())){
            if(StringUtils.isNotBlank(tmCustomAlert.getComparisonOperatorOne())){
                int a = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueOne()));
                //比较符为大于
                if("1".equals(tmCustomAlert.getComparisonOperatorOne())){
                    //电压差值大于告警定义范围值
                    if(a>0){
                        flag = false;
                    }
                //比较符为大于等于
                }else if("2".equals(tmCustomAlert.getComparisonOperatorOne())){
                    if(a>=0){
                        flag = false;
                    }
                }
            }
            if(StringUtils.isNotBlank(tmCustomAlert.getComparisonOperatorTwo())){
                int a = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueTwo()));
                //比较符为小于
                if("3".equals(tmCustomAlert.getComparisonOperatorTwo())){
                    //电压差值大于告警定义范围值
                    if(a<0){
                        flag = false;
                    }
                //比较符为大于等于
                }else if("4".equals(tmCustomAlert.getComparisonOperatorTwo())){
                    if(a<=0){
                        flag = false;
                    }
                }
            }
        //逻辑操作符为与
        }else if("1".equals(tmCustomAlert.getLogicalSymbol())){
            boolean m=true,n=true;
            int a = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueOne()));
            int b = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueTwo()));
            //比较符为大于
            if("1".equals(tmCustomAlert.getComparisonOperatorOne())){
                //电压差值大于告警定义范围值
                if(a>0){
                    m = false;
                }
            //比较符为大于等于
            }else if("2".equals(tmCustomAlert.getComparisonOperatorOne())){
                if(a>=0){
                    m = false;
                }
            }
            //比较符为小于
            if("3".equals(tmCustomAlert.getComparisonOperatorTwo())){
                //电压差值大于告警定义范围值
                if(b<0){
                    n = false;
                }
            //比较符为大于等于
            }else if("4".equals(tmCustomAlert.getComparisonOperatorTwo())){
                if(b<=0){
                    n = false;
                }
            }
            flag = m&&n ;
        //逻辑操作符为或
        }else if("2".equals(tmCustomAlert.getLogicalSymbol())){
            boolean m=true,n=true;
            int a = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueOne()));
            int b = differences.compareTo(new BigDecimal(tmCustomAlert.getComparisonValueTwo()));
            //比较符为大于
            if("1".equals(tmCustomAlert.getComparisonOperatorOne())){
                //电压差值大于告警定义范围值
                if(a>0){
                    m = false;
                }
            //比较符为大于等于
            }else if("2".equals(tmCustomAlert.getComparisonOperatorOne())){
                if(a>=0){
                    m = false;
                }
            }
            //比较符为小于
            if("3".equals(tmCustomAlert.getComparisonOperatorTwo())){
                //电压差值小于告警定义范围值
                if(b<0){
                    n = false;
                }
            //比较符为小于等于
            }else if("4".equals(tmCustomAlert.getComparisonOperatorTwo())){
                if(b<=0){
                    n = false;
                }
            }
            flag = m||n ;
        }
        return flag;
    }

}
